package yunjiao.javatutorials.guava.concurrent.event;

import com.google.common.util.concurrent.ListenableFuture;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 同步等待响应
 *
 * @author yangyunjiao
 */
public class EventProcessorSyncExample {
    public static void main(String[] args) throws Exception {
        EventProcessor processor = new EventProcessor();
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 发送请求
        ListenableFuture<String> future = processor.sendRequest("REQ-001", "获取用户信息");

        // 模拟在另一个线程中处理响应
        executor.execute(() -> {
            try {
                Thread.sleep(2000); // 模拟处理时间
                processor.handleResponse("REQ-001", "用户信息: {name: '张三', age: 30}");
            } catch (InterruptedException e) {
                processor.handleError("REQ-001", "处理中断");
            }
        });

        try {
            // 同步等待结果
            String result = future.get();
            System.out.println("收到结果: " + result);
        } catch (ExecutionException e) {
            System.out.println("请求失败: " + e.getCause().getMessage());
        }

        executor.shutdown();
    }
}
